<!--
 * Description: FD 不同版本之间的对比组件
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Qiuxue.Wu
 * Date: 2020/06/22 13:30
-->
<template>
  <div class="fd-compare-view">
    <div class="custom-top">
      <el-row>
        <!--FD Base-->
        <el-col :span="2">
          <el-select
            v-model="queryForm.fdIdLeft"
            clearable
            filterable
            placeholder="FD"
            size="small"
            style="width: 100%; height: 30px"
            @change="changeLeft"
          >
            <el-option
              v-for="item in fdFilterList"
              :key="item.fdId"
              :label="item.fdId"
              :value="item.fdId"
            >
              {{ item.fdId }}
            </el-option>
          </el-select>
        </el-col>

        <!--FD 版本-->
        <el-col :span="2" style="margin-left: 5px">
          <el-select
            v-model="queryForm.fdVersionLeft"
            clearable
            filterable
            placeholder="版本"
            size="small"
            style="width: 100%"
          >
            <el-option v-for="item in fdVersionLeftList" :key="item" :label="item" :value="item">
              {{ item }}
            </el-option>
          </el-select>
        </el-col>

        <!--FD New/Base-->
        <el-col :span="2" style="margin-left: 5px">
          <el-select
            v-model="queryForm.fdNBLeft"
            clearable
            filterable
            placeholder="Base"
            size="small"
            style="width: 100%"
          >
            <el-option v-for="item in typeList" :key="item" :label="item" :value="item">
              {{ item }}
            </el-option>
          </el-select>
        </el-col>

        <el-col :span="1">
          <div class="vs">vs</div>
        </el-col>

        <!--FD New-->
        <el-col :span="2">
          <el-select
            v-model="queryForm.fdIdRight"
            clearable
            filterable
            placeholder="FD"
            size="small"
            style="width: 100%; height: 30px"
            @change="changeRight"
          >
            <el-option
              v-for="item in fdFilterList"
              :key="item.fdId"
              :label="item.fdId"
              :value="item.fdId"
            >
              {{ item.fdId }}
            </el-option>
          </el-select>
        </el-col>

        <!--FD 版本-->
        <el-col :span="2" style="margin-left: 5px">
          <el-select
            v-model="queryForm.fdVersionRight"
            clearable
            filterable
            placeholder="版本"
            size="small"
            style="width: 100%"
          >
            <el-option v-for="item in fdVersionRightList" :key="item" :label="item" :value="item">
              {{ item }}
            </el-option>
          </el-select>
        </el-col>

        <!--FD New/Base-->
        <el-col :span="2" style="margin-left: 5px">
          <el-select
            v-model="queryForm.fdNBRight"
            clearable
            filterable
            placeholder="Base"
            size="small"
            style="width: 100%"
          >
            <el-option v-for="item in typeList" :key="item" :label="item" :value="item">
              {{ item }}
            </el-option>
          </el-select>
        </el-col>

        <el-col :span="2">
          <el-button
            v-if="$hasPer('compare')"
            class="btn-custom"
            icon="el-icon-copy-document"
            plain
            size="small"
            style="margin-left: 10px"
            type="primary"
            @click="getFdLeftAndRightList"
          >
            {{ $t('button.compare') }}
          </el-button>
        </el-col>
      </el-row>
    </div>
    <div class="custom-bottom">
      <VirtualTable
        :header-cell-style="$headerCellStyle"
        :headerCellStyle="headerCellStyle"
        :table="fdCompareResultList"
      >
        <!-- 序号 -->
        <Cell dir="left" fix="left" :label="$t('FdData.rowNo')" :width="50">
          <template slot-scope="scope">
            <span>{{ scope.index + 1 }}</span>
          </template>
        </Cell>
        <!-- 比较内容 -->
        <Cell
          v-for="dir in dirList"
          :key="dir"
          :dir="dir"
          :label="dir === 'left' ? leftLabel : rightLabel"
        >
          <!-- rdFunction -->
          <Cell :dir="dir" :label="$t('FdData.rdFunction')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ scope.row[dir].rdFunction }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- category -->
          <Cell :dir="dir" :label="$t('FdData.category')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ scope.row[dir].category }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- itemNo -->
          <Cell :dir="dir" :label="$t('FdData.itemNo')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ scope.row[dir].itemNo }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- rdOwner -->
          <Cell :dir="dir" :label="$t('FdData.rdOwner')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ scope.row[dir].rdOwner }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- trackingOption -->
          <Cell :dir="dir" :label="$t('FdData.trackingOption')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ scope.row[dir].trackingOption }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- optionType -->
          <Cell :dir="dir" :label="$t('FdData.optionType')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ scope.row[dir].optionType }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- basePartName -->
          <Cell :dir="dir" :label="$t('FdData.basePartName')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ propVal(dir, scope, 'PartName') }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- basePartNo -->
          <Cell :dir="dir" :label="$t('FdData.basePartNo')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ propVal(dir, scope, 'PartNo') }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- newTempPartNo -->
          <Cell
            v-if="showColumn(dir)"
            :dir="dir"
            :label="$t('FdData.newTempPartNo')"
            prop="newTempPartNo"
          />

          <!-- basePartDesc -->
          <Cell :dir="dir" :label="$t('FdData.basePartDesc')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ propVal(dir, scope, 'PartDesc') }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- baseMaterialType -->
          <Cell :dir="dir" :label="$t('FdData.baseMaterialType')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ propVal(dir, scope, 'MaterialType') }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- baseMaterialColor -->
          <Cell :dir="dir" :label="$t('FdData.baseMaterialColor')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ propVal(dir, scope, 'MaterialColor') }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- baseSize -->
          <Cell :dir="dir" :label="$t('FdData.baseSize')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ propVal(dir, scope, 'Size') }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- baseQty -->
          <Cell :dir="dir" :label="$t('FdData.baseQty')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ propVal(dir, scope, 'Qty') }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- baseIdProcess -->
          <Cell :dir="dir" :label="$t('FdData.baseIdProcess')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ propVal(dir, scope, 'IdProcess') }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- baseSupplier -->
          <Cell :dir="dir" :label="$t('FdData.baseSupplier')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ propVal(dir, scope, 'Supplier') }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- baseSupplierPn -->
          <Cell :dir="dir" :label="$t('FdData.baseSupplierPn')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ propVal(dir, scope, 'SupplierPn') }}
              </DeleteLine>
            </template>
          </Cell>

          <!-- newTooling -->
          <Cell
            v-if="showColumn(dir)"
            :dir="dir"
            :label="$t('FdData.newTooling')"
            prop="newTooling"
          />

          <!-- baseRemark -->
          <Cell :dir="dir" :label="$t('FdData.baseRemark')">
            <template slot-scope="scope">
              <DeleteLine :isLine="scope.row[dir].delete">
                {{ propVal(dir, scope, 'Remark') }}
              </DeleteLine>
            </template>
          </Cell>
        </Cell>

        <Cell fix="right" label="Compare State">
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.right.state"
              :disable-transitions="true"
              effect="dark"
              size="mini"
              :type="stateType(scope.row.right.state)"
            >
              {{ scope.row.right.state }}
            </el-tag>
          </template>
        </Cell>

        <Cell fix="right" label="Compare Detail" :width="300">
          <template slot-scope="scope">
            <el-link
              v-for="(propItem, index) in scope.row.right.diffColumns"
              :key="index"
              style="margin-right:10px"
              type="success"
              :underline="false"
              @click="rowDetail(scope.index, scope.row)"
            >
              {{ headLabel[propItem] }}
            </el-link>
          </template>
        </Cell>
      </VirtualTable>
    </div>

    <!-- 估价对话框 -->
    <BaseDialog
      v-if="detailDialogVisible"
      :title="$t('button.view')"
      :visible.sync="detailDialogVisible"
      width="1000px"
    >
      <FdCompareDetail
        :fd-compare-result-list="fdCompareResultList"
        :input-data="currentEditRow"
        :query-form="queryForm"
        @cancel="detailDialogVisible = false"
      />
    </BaseDialog>
  </div>
</template>
<script>
import { fdList } from '@/api/quote/fd'
import { fdRowListPart } from '@/api/quote/fd-row'
import DeleteLine from '@/widgets/DeleteLine'
import FdCompareDetail from './FdCompareDetail'
import Cell from '@/widgets/VirtualTable/Cell'
import VirtualTable from '@/widgets/VirtualTable/Table'

export default {
  name: 'FdCompareView',
  components: { DeleteLine, FdCompareDetail, VirtualTable, Cell },
  data() {
    return {
      // 所有fd数据
      fdListData: [],
      // 去重fd数据（fdId）
      fdFilterList: [],
      // new base 集合
      typeList: ['Base', 'New'],
      // 查询表单
      queryForm: {
        fdIdLeft: '',
        fdVersionLeft: '',
        fdNBLeft: '',

        fdIdRight: '',
        fdVersionRight: '',
        fdNBRight: ''
      },
      // table 数据
      formData: [],
      // fd 左边搜索的条件查询数据
      fdLeftTableList: [],
      // 新增对话框可见标识
      detailDialogVisible: false,
      // 当前行数据
      currentEditRow: {},
      // baseKeyList
      baseKeyList: [
        'basePartName',
        'basePartNo',
        'basePartDesc',
        'baseMaterialType',
        'baseMaterialColor',
        'baseSize',
        'baseQty',
        'baseIdProcess',
        'baseSupplier',
        'baseSupplierPn',
        'baseRemark'
      ],
      // newKeyList
      newKeyList: [
        'newPartName',
        'newPartNo',
        'newPartDesc',
        'newMaterialType',
        'newMaterialColor',
        'newSize',
        'newQty',
        'newIdProcess',
        'newSupplier',
        'newSupplierPn',
        'newRemark'
        // 'newTooling',
        // 'newTempPartNo'
      ],
      headLabel: {
        basePartName: 'Part Name',
        basePartNo: 'Part Number',
        basePartDesc: 'Part Description',
        baseMaterialType: 'Material Type',
        baseMaterialColor: 'Material Color',
        baseSize: 'Size',
        baseQty: 'Qty',
        baseIdProcess: 'ID Process',
        baseSupplier: 'Supplier',
        baseSupplierPn: 'Supplier PN',
        baseRemark: 'Remarks',

        newPartName: 'Part Name',
        newPartNo: 'Part Number',
        newPartDesc: 'Part Description',
        newMaterialType: 'Material Type',
        newMaterialColor: 'Material Color',
        newSize: 'Size',
        newQty: 'Qty',
        newIdProcess: 'ID Process',
        newSupplier: 'Supplier',
        newSupplierPn: 'Supplier PN',
        newRemark: 'Remarks'
      },
      // fd 右边搜索的条件查询数据
      //   fdRightTableList: [],
      // fd 左边和右边合并的数据
      //   fdMergeTableList: [],
      // fd 比对之后的数据
      fdCompareResultList: [],
      dirList: ['left', 'right']
    }
  },
  computed: {
    // 根据左边选中的fdId获取这个fdId版本的集合
    fdVersionLeftList() {
      const fdId = this.queryForm.fdIdLeft
      const versionArr = []
      this.fdListData.forEach(item => {
        if (item.fdId === fdId) {
          versionArr.push(item.version)
        }
      })
      return versionArr
    },
    // 根据右边选中的fdId获取这个fdId版本的集合
    fdVersionRightList() {
      const fdId = this.queryForm.fdIdRight
      const versionArr = []
      this.fdListData.forEach(item => {
        if (item.fdId === fdId) {
          versionArr.push(item.version)
        }
      })
      return versionArr
    },
    // 左边label
    leftLabel() {
      if (this.queryForm.fdIdLeft) {
        return `${this.queryForm.fdIdLeft}  ${this.queryForm.fdVersionLeft}  ${this.queryForm.fdNBLeft}`
      } else {
        return 'Left Project'
      }
    },
    // 左边label
    rightLabel() {
      if (this.queryForm.fdIdRight) {
        return `${this.queryForm.fdIdRight}  ${this.queryForm.fdVersionRight}  ${this.queryForm.fdNBRight}`
      } else {
        return 'Right Project'
      }
    }
  },
  watch: {
    fdListData: {
      handler: function() {
        const newArr = []
        this.fdListData.forEach(item => {
          for (const newItem of newArr) {
            if (item.fdId === newItem.fdId) {
              return
            }
          }
          newArr.push(item)
        })
        this.fdFilterList = newArr
      }
    }
  },
  mounted() {
    this.pageDataInit()
  },
  methods: {
    propVal(direction, scope, prop) {
      if (direction === 'left') {
        return this.queryForm.fdNBLeft === 'New'
          ? scope.row.left['new' + prop]
          : scope.row.left['base' + prop]
      } else {
        return this.queryForm.fdNBRight === 'New'
          ? scope.row.right['new' + prop]
          : scope.row.right['base' + prop]
      }
    },
    // new中有些列在base中是没有的
    showColumn(direction) {
      if (direction === 'left') {
        return this.queryForm.fdNBLeft === 'New'
      } else {
        return this.queryForm.fdNBRight === 'New'
      }
    },
    /* 页面数据初始化*/
    async pageDataInit() {
      try {
        const res = await fdList({})
        this.fdListData = res.data
      } catch (error) {
        console.log(error)
      }
    },

    changeLeft() {
      this.queryForm.fdVersionLeft = ''
    },

    changeRight() {
      this.queryForm.fdVersionRight = ''
    },

    // 比较结果的状态对应的tag类型
    stateType(type) {
      if (type === 'same') {
        return 'success'
      } else if (type === 'change') {
        return 'info'
      } else {
        return 'warning'
      }
    },

    // 比较结果left中delete，如果delete为true添加line
    lineClass(isDelete) {
      if (isDelete) {
        return 'line'
      }
    },

    rowDetail(index, row) {
      this.currentEditRow = this.$deepCopy(row)
      this.detailDialogVisible = true
    },

    // 获取左右两边的数据集合
    async getFdLeftAndRightList() {
      for (const key in this.queryForm) {
        if (!this.queryForm[key]) {
          this.$message({
            message: '比对条件未填写完整',
            type: 'error',
            duration: 1500
          })
          return
        }
      }
      try {
        const res1 = await fdRowListPart({
          fdId: this.queryForm.fdIdLeft,
          version: this.queryForm.fdVersionLeft
        })
        const fdLeftTableList = res1.data
        const res2 = await fdRowListPart({
          fdId: this.queryForm.fdIdRight,
          version: this.queryForm.fdVersionRight
        })
        const fdRightTableList = res2.data

        // 初始化默认左边的行数据都是删除状态
        for (const leftRow of fdLeftTableList) {
          leftRow.delete = true
        }
        /*
         比对左边是否存在同样的数据，判断是否同样的依据如下：
         1.如果Part Number不为空，则key值使用RD Function + Category + Tracking & Option + Part Number，
         基于此识别Add / Delete / Change
         2.如果Part Number为空，则key值使用RD Function + Category + Tracking&Option + Part Name + Part Description，
         基于此识别Add / Delete / Change
          */
        for (const rightRowIndex in fdRightTableList) {
          const rightRow = fdRightTableList[rightRowIndex]
          const rightSelectType = this.queryForm.fdNBRight
          const partNo = rightSelectType === 'New' ? rightRow.newPartNo : rightRow.basePartNo
          const rightPartName =
            rightSelectType === 'New' ? rightRow.newPartName : rightRow.basePartName
          const rightPartDesc =
            rightSelectType === 'New' ? rightRow.newPartDesc : rightRow.basePartDesc
          const rightKey = partNo
            ? rightRow.rdFunction + rightRow.category + rightRow.trackingOption + partNo
            : rightRow.rdFunction +
              rightRow.category +
              rightRow.trackingOption +
              rightPartName +
              rightPartDesc
          for (const leftRowIndex in fdLeftTableList) {
            const leftRow = fdLeftTableList[leftRowIndex]
            const leftSelectType = this.queryForm.fdNBLeft
            const leftPartName =
              leftSelectType === 'New' ? leftRow.newPartName : leftRow.basePartName
            const leftPartDesc =
              leftSelectType === 'New' ? leftRow.newPartDesc : leftRow.basePartDesc
            const leftPartNo = leftSelectType === 'New' ? leftRow.newPartNo : leftRow.basePartNo

            const leftKey = partNo
              ? leftRow.rdFunction + leftRow.category + leftRow.trackingOption + leftPartNo
              : leftRow.rdFunction +
                leftRow.category +
                leftRow.trackingOption +
                leftPartName +
                leftPartDesc
            // 找到一样的，比较数据是否变化
            if (leftKey === rightKey) {
              leftRow.delete = false
              // 比较new base
              if (this.compareRow(leftRow, rightRow)) {
                rightRow.state = 'same'
              } else {
                rightRow.state = 'change'
                rightRow.rightRowIndex = rightRowIndex
                rightRow.relateLeftRowIndex = leftRowIndex
              }
              break
            }
          }
          // 遍历左边列表没有找到相同key的数据就标记右边这行数据为add
          if (!rightRow.state) {
            rightRow.state = 'add'
          }
        }
        const count =
          fdRightTableList.length >= fdLeftTableList.length
            ? fdRightTableList.length
            : fdLeftTableList.length
        this.fdCompareResultList = []
        for (let i = 0; i < count; i++) {
          this.fdCompareResultList.push({
            id: fdLeftTableList[i] ? fdLeftTableList[i].fdRowId : fdRightTableList[i].fdRowId,
            rowNo: i,
            left: fdLeftTableList[i] ? fdLeftTableList[i] : {},
            right: fdRightTableList[i] ? fdRightTableList[i] : {}
          })
        }
        console.log(this.fdCompareResultList)
      } catch (error) {
        console.log(error)
      }
    },

    // 比较一行数据是否相同
    compareRow(leftRow, rightRow) {
      let isEqual = true
      // 不同列（右边相对左边不同的列）
      const diffColumns = []
      const leftSelectType = this.queryForm.fdNBLeft
      const rightSelectType = this.queryForm.fdNBRight
      //   const leftKeyIndexList = Object.keys(leftRow).filter(item => item.indexOf(leftSelectType).toLowerCase() > -1)
      //   const rightKeyIndexList = Object.keys(rightRow).filter(item => item.indexOf(rightSelectType).toLowerCase() > -1)
      if (leftSelectType === 'New' && rightSelectType === 'New') {
        for (const keyItem of this.newKeyList) {
          if (rightRow[keyItem] !== leftRow[keyItem]) {
            isEqual = false
            diffColumns.push(keyItem)
          }
        }
      } else if (leftSelectType === 'New' && rightSelectType === 'Base') {
        for (const keyIndex in this.newKeyList) {
          if (leftRow[this.newKeyList[keyIndex]] !== rightRow[this.baseKeyList[keyIndex]]) {
            isEqual = false
            diffColumns.push(this.baseKeyList[keyIndex])
          }
        }
      } else if (leftSelectType === 'Base' && rightSelectType === 'New') {
        for (const keyIndex in this.baseKeyList) {
          if (leftRow[this.baseKeyList[keyIndex]] !== rightRow[this.newKeyList[keyIndex]]) {
            isEqual = false
            diffColumns.push(this.newKeyList[keyIndex])
          }
        }
      } else {
        //  leftSelectType === 'Base' && rightSelectType === 'Base'
        for (const keyItem of this.baseKeyList) {
          if (rightRow[keyItem] !== leftRow[keyItem]) {
            isEqual = false
            diffColumns.push(keyItem)
          }
        }
      }
      rightRow.diffColumns = diffColumns
      return isEqual
    },

    headerCellStyle({ col, depth, td }) {
      if (td.dir === 'left') {
        return { backgroundColor: '#ffff' }
      } else if (td.dir === 'right') {
        return { backgroundColor: '#d6d6d6' }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.fd-compare-view {
  position: fixed;
  top: 64px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  padding: 0px 25px 16px 20px;
}
.custom-top {
  height: 60px;
  padding-top: 12px;
}
.custom-bottom {
  position: absolute;
  top: 60px;
  bottom: 20px;
  left: 20px;
  right: 25px;
}
.vs {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 30px;
  font-size: 26px;
  font-weight: 600;
  color: #333;
}
</style>
